package com.dunjx.oauth.service.impl;

import com.dunjx.oauth.service.UserLoginService;
import com.dunjx.oauth.uitl.AuthToken;
import entity.Result;
import entity.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * @author appyH
 */
@Slf4j
@Service
public class
UserLoginServiceImpl implements UserLoginService {

    /**
     * 实现请求发送
     */
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 登录实现
     *
     * @param username
     * @param password
     * @param clientId
     * @param clientSecret
     * @param grantType
     */
    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret, String grantType) {
        ServiceInstance choose = loadBalancerClient.choose("user-auth");
        String uri = choose.getUri().toString() + "/oauth/token";
        log.info("本服务的URL为{}", uri);
        //封装请求参数
        MultiValueMap<String, String> parameterMap = new LinkedMultiValueMap<>();
        parameterMap.add("grant_type", grantType);
        parameterMap.add("username", username);
        parameterMap.add("password", password);
        // 封装请求头信息
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", "Basic " + Base64.getEncoder().encodeToString(new String(clientId + ":" + clientSecret).getBytes()));
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(parameterMap, headers);
        // 调用请求地址
        ResponseEntity<Map> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, Map.class);

        Map body = responseEntity.getBody();


        // 参数传递
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken((body.get("access_token")).toString());
        authToken.setRefreshToken((body.get("refresh_token")).toString());
        authToken.setJti((body.get("jti")).toString());
        return authToken;

    }
}
